package com.hw.backapi.interceptor;

import cn.hutool.json.JSONObject;
import com.hw.backapi.context.UserAuthContext;
import com.hw.common.utils.HttpUtil;
import com.hw.model.common.ResultCode;
import com.hw.model.entity.AdminPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * token登录拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    UserAuthContext userAuthContext;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try{
            AdminPO userInfo = userAuthContext.getUserInfo();
            if( userInfo != null ){
                return true;
            }
        }catch (Exception e){
            log.info("拦截器失败：{}",e.getMessage());
        }
        Map<String, Object> result = new HashMap<>();
        result.put("status", ResultCode.NOLOGIN);
        result.put("message", "未登录");
        HttpUtil.writeJson(response, new JSONObject(result));
        return false;
    }
}
